﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using workflowMVC.Models;
using System.Web.Security;
using System.Web.Mvc;
using System.Web.Routing;
using DataTool;
using DataTables;
using Common;
using OneGateWF;
namespace workflowMVC
{
    public class Util
    {
        public static wfdbEntities entity = new wfdbEntities();

        static public readonly string detail = "ui-icon ui-icon-folder-open fl";
        static public readonly string edit = "ui-icon ui-icon-wrench fl";
        static public readonly string delete = "ui-icon ui-icon-trash fl";
        static public readonly string reject = "ui-icon ui-icon-cancel fl";
        static public readonly string validate = "ui-icon ui-icon-check fl";
        static public readonly string chose = "ui-icon ui-icon-check fl";
        static public readonly string send = "ui-icon ui-icon-mail-closed fl";
        static public readonly string addnew = "ui-icon ui-icon-plusthick fl";
        static public readonly string warning = "ui-icon ui-icon-flag fl";
        static public readonly string lockacc = "ui-icon ui-icon-locked fl";
        static public readonly string unlockacc = "ui-icon ui-icon-unlocked fl";
        static public readonly string calculator = "ui-icon ui-icon-calculator fl";
        static public string getsTableLink(object spanHtmlAtt, object aHtmlAtt)
        {

            TagBuilder span = new TagBuilder("span");
            span.MergeAttributes(new RouteValueDictionary(spanHtmlAtt));

            TagBuilder a = new TagBuilder("a");
            a.MergeAttributes(new RouteValueDictionary(aHtmlAtt));


            a.InnerHtml = span.ToString();
            return a.ToString(); ;
        }

        static public void TableLinkMiscCheck(List<string> x,string url)
        {
            Guid idx = Guid.Parse(x[5]);
            x[5] =
            Util.getsTableLink
            (new { @class = Util.detail },
            new { title = "Xem", href = url+"/"+ x[5] });
            if (Util.IsSuspectSpam(1, idx))
            {
                x[5] += Util.getsTableLink
            (new { @class = Util.warning },
            new
            {
                title = "Hành vi nghi ngờ spam",
                href = "../Account/StudentDetail/"+ x[2] + "#logs"
            });
            }
            x[2] = "<a href='../Account/StudentDetail/"+ x[2] + "'>" + x[2] + "</a>";
        }

        static public string getName(string Username)
        {
            wfdbEntities db = new wfdbEntities();
            if (db.STAFFs.Select(x => x.UserName).Contains(Username))
                return db.STAFFs.FirstOrDefault(x => x.UserName == Username).RealName;
            else
                return db.STUDENTs.FirstOrDefault(x => x.NumCode == Username).Name;
        }

        static public void TableLinkMiscApprove(List<string> x, string url)
        {
             x[5] = Util.getsTableLink(new { @class = Util.detail }, new { title = "Xem", href = url+"/"+x[5] });
        }

        static public string getSYear(int StartYear)
        {
            int result = DateTime.Now.Year - StartYear;
            if (DateTime.Now.Month >= 8)
                result += 1;
            return result.ToString();
        }

        static public string getStudentName(string NumCode)
        {
            wfdbEntities db = new wfdbEntities();
            return db.STUDENTs.Where(x => x.NumCode == NumCode).FirstOrDefault().Name;
        }

        #region Status Codes
        public static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion

        internal static List<string> GetRolesFromUser(string UserName)
        {
            wfdbEntities wf = new wfdbEntities();
            return wf.aspnet_Users.Where(x => x.UserName == UserName).SingleOrDefault().aspnet_Roles.Select(x => x.RoleName).ToList();
            
        }

        //static public FormatedList SimpleTaskListData(HttpRequestBase Request,Func<SimpleTaskPPFromInstStore, bool> kind, Func<SimpleTaskPPFromInstStore, bool> status)
        //{
        //    wfdbEntities db = new wfdbEntities();
        //    var data = SimpleTaskPPFromInstStore.getTask()
        //        .AsEnumerable().Where(kind).Where(status)
        //        .Select(x => new ProcessingTaskListModel()
        //        {
        //            date = (DateTime)x.Date,
        //            id = x.InstanceId,
        //            Owner= x.NumCode.ToString(),
        //            status = db.TASKSTATUS.Where(z => z.Id == (byte)x.Status).FirstOrDefault().Description,
        //            taskkind = db.TASKKINDs.Where(z => z.Id == (byte)x.TaskKind).FirstOrDefault().Description,

        //        });
        //    return new DataTableParser<ProcessingTaskListModel>(Request, data.AsQueryable()).Parse();
        //}

        static public FormatedList ValidateTaskListData(HttpRequestBase Request, Func<TASK, bool> whereclause)
        {
            wfdbEntities db = new wfdbEntities();
            var data = db.TASKs.Where(whereclause).AsEnumerable()
                .Select(x => new ProcessingTaskListModel()
                {
                    date = x.LOGs.Where(l => l.Kind == 1).FirstOrDefault().Date.Value ,
                    id = x.Id,
                    OwnerNumcode = x.NumCode,
                    OwnerName = db.STUDENTs.Where(z => z.NumCode == x.NumCode).FirstOrDefault().Name,
                    status = x.TASKSTATU.Description,
                    taskkind = x.TASKKIND.Description,

                });
            return new DataTableParser<ProcessingTaskListModel>(Request, data.AsQueryable()).Parse();
        }

        static public string getFormHtmlCode(string sUrl)
        {
            return @"<iframe width='100%' height='900px' src ='" + sUrl + @"'></iframe>";
        }

        static public ExcemptTuitionVS getExcempTuitionVS(ExcemptTuitionTaskRevModel m, bool Result, string Username, Guid Id)
        {
            return new ExcemptTuitionVS
            {
                IsAgree = Result,
                Note = m.NewNote,
                UserName = Username,
                UserRole = Util.GetRolesFromUser(Username),
                ValidTime = DateTime.Now,
                Fault = m.Fault,
                Tuition = m.Tuition                
            };
        }
        static public ValidateSession getValidateSession(string Note, bool Result, string Username, Guid Id)
        {
            return new ValidateSession
            {
                IsAgree = Result,
                UserName = Username,
                UserRole = Util.GetRolesFromUser(Username),
                ValidTime = DateTime.Now,
                Note = Note
            };
        }

        internal static void getConfirmStuForm(HttpContextBase HttpContext, Guid Id)
        {
            wfdbEntities db = new wfdbEntities();
            var t = db.TASKs.Where(x => x.Id == Id).FirstOrDefault();
            string studentNumCode = t.NumCode.ToString();
            var Student = db.STUDENTs.Where(x => x.NumCode == studentNumCode).SingleOrDefault();
            HttpContext.Session["Report_Kind"] = "ConfirmStudentForm";
            HttpContext.Session["Report_Name"] = Student.Name;
            HttpContext.Session["Report_NumCode"] = Student.NumCode;
            HttpContext.Session["Report_Birthday"] = Student.DoB;
            HttpContext.Session["Report_Address"] = Student.Address;
            HttpContext.Session["Report_Class"] = Student.Class;
            HttpContext.Session["Report_StartYear"] = Student.StartYear;
            HttpContext.Session["Report_TimeLast"] = Student.TIMELAST1.Description;
            HttpContext.Session["Report_EduMode"] = Student.EDUMODE1.Description;
            HttpContext.Session["Report_SYear"] = DateTime.Now.Year - Student.StartYear;
            HttpContext.Session["Report_Reason"] = t.Reason.ToString();
            HttpContext.Session["Report_Department"] = Student.CLASS1.DEPARTMENT1.Description;
        }

        public static List<string> getLogsForWebPage(Guid Id)
        {
            wfdbEntities db = new wfdbEntities();
            var t = db.TASKs.Where(x => x.Id == Id).FirstOrDefault();
            if (t == null)
                throw new Exception();
            List<string> Logs = new List<string>();
            foreach (var item in t.LOGs.OrderByDescending(x => x.Date))
            {
                Logs.Add(item.Date+" -- "+item.LOGKIND.Description+" Bởi "+ item.Writer +"--ghi chú :"+item.Note);
            }
            return Logs;
        }

        internal static void getExcemptStudentForm(HttpContextBase HttpContext, Guid Id)
        {
            wfdbEntities db = new wfdbEntities();
            var m = db.TASKs.Where(x => x.Id == Id).FirstOrDefault();
            string studentNumCode = m.NumCode.ToString();
            var Student = db.STUDENTs.Where(x => x.NumCode == studentNumCode).SingleOrDefault();
            HttpContext.Session["Report_Kind"] = "ExcemptTuitionForm";
            HttpContext.Session["Report_Name"] = Student.Name;
            HttpContext.Session["Report_NumCode"] = Student.NumCode;
            HttpContext.Session["Report_Department"] = Student.CLASS1.DEPARTMENT1.Description;
            HttpContext.Session["Report_Birthday"] = Student.DoB;
            HttpContext.Session["Report_Hometown"] = m.HomeTown;
            HttpContext.Session["Report_ParentName"] = m.ParentName;
            HttpContext.Session["Report_Street"] = m.Street;
            HttpContext.Session["Report_Ward"] = m.Ward;
            HttpContext.Session["Report_District"] = m.District;
            HttpContext.Session["Report_Province"] = m.Province;
            HttpContext.Session["Report_Type"] = m.Type;
            HttpContext.Session["Report_Class"] = Student.Class;
            HttpContext.Session["Report_SYear"] = Util.getSYear(Student.StartYear.Value);
            HttpContext.Session["Report_StartYear"] = Student.StartYear;
            HttpContext.Session["Report_TimeLast"] = Student.TIMELAST1.Description;
            HttpContext.Session["Report_Tuition"] = m.Tuition != null ? m.Tuition : "___" ;
            HttpContext.Session["Report_Fault"] = m.Fault != null ? m.Fault : "___";
        }

        internal static void getStudentCardForm(HttpContextBase HttpContext, Guid Id)
        {
            wfdbEntities db = new wfdbEntities();
            var m = db.TASKs.Where(x => x.Id == Id).FirstOrDefault();
            string studentNumCode = m.NumCode.ToString();
            var Student = db.STUDENTs.Where(x => x.NumCode == studentNumCode).SingleOrDefault();
            HttpContext.Session["Report_Kind"] = "StudentCardForm";
            HttpContext.Session["Report_Name"] = Student.Name;
            HttpContext.Session["Report_NumCode"] = Student.NumCode;
            HttpContext.Session["Report_Birthday"] = Student.DoB.Value.ToShortDateString();
            HttpContext.Session["Report_EduMode"] = Student.EDUMODE1.Description;
            HttpContext.Session["Report_SYear"] = DateTime.Now.Year - Student.StartYear;
            HttpContext.Session["Report_Reason"] = m.Reason;
            HttpContext.Session["Report_Department"] = Student.CLASS1.DEPARTMENT1.Description;
        }

        internal static bool IsSuspectSpam(int Kind, Guid Id)
        {
            wfdbEntities db = new wfdbEntities();
            var t = db.TASKs.Where(x => x.Id == Id).FirstOrDefault();
            var NumCode = t.NumCode;
            byte kind = t.Kind.Value;
            DateTime d = t.LOGs.Where(x => x.Kind == 1).FirstOrDefault().Date.Value.Subtract(new TimeSpan(7,0,0,0,0));
            if(db.TASKs.Where(x => x.NumCode == NumCode && x.Kind == kind && x.LOGs.Where(z => z.Kind ==1).FirstOrDefault().Date > d).Count() > 3)
            {
                return true;
            }
            return false;
        }

        internal static string getLinkForContest(string p,UrlHelper Url)
        {
            wfdbEntities db = new wfdbEntities();
            Guid id= Guid.Parse(p);
            var c=db.CONTESTs.SingleOrDefault(x => x.Id == id);
            return "<a href='" + Url.Action("Detail", new { id = p }) + "'>" + c.Title + "</a>";
        }
    }
}